#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QCryptographicHash>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mainui_1=new mainui;
    mainui_1->createdatabase(); //创建数据库
    qDebug()<<"create database"<<endl;
    ui->lineEdit->setText("admin");
    ui->lineEdit_2->setText("123456");

}

MainWindow::~MainWindow()
{
    delete ui;
}
QString MainWindow::MD5encryption(QString s)
{
    QString rslt;
    rslt=QCryptographicHash::hash(s.toLatin1(),QCryptographicHash::Md5).toHex();
    return rslt;
}
void MainWindow::on_pushButton_clicked()
{
    createtable();
    mainui_1->database.open();
    //登录认证
    int valid=0;
    QString username,password,user0,pass0;
    username=ui->lineEdit->text();
    password=MD5encryption(ui->lineEdit_2->text());
    if(username!="admin"){//限制管理员登录
        QMessageBox::information(0,"infor","请用admin账户登录");
        return;
    }
    QSqlQuery query;
    query.exec("select * from yonghu");
    while( query.next()){//指向第一条记录
    user0=query.value(1).toString();
    pass0=query.value(2).toString();
    if(!QString::compare(password,pass0)&&!QString::compare(username,user0)) //查到admin用户记录，限制管理员登录且密码hash值匹配
    {
    valid=1;
    }
    }
    if(valid){
        connect(mainui_1,SIGNAL(sendsignal_1()),this,SLOT(show()));//当退出子界面时，调用主界面的show()函数
        mainui_1->show();
        this->hide() ;
    }else{
        QMessageBox::about(NULL, "输入错误", "重新输入");
    }
}

void MainWindow::createtable()
{
    if (!mainui_1->database.open())
    {
        qDebug() << "Error: Failed to connect database." << mainui_1->database.lastError();
    }
    else
    {
        //创建用户表
        QSqlQuery query1;
        if(!mainui_1->database.tables().contains("yonghu")){        //用户信息表
          query1.exec("create table yonghu (id int primary key, "
                           "username char(20), password char(32))");//保存id,用户名和密码hash值的数组
          qDebug()<<"create table yonghu"<<endl;

          //创建表时添加admin及其密码哈希值
          QSqlQuery query;
           QString str;
           str="123456";
           QString md5rslt=MD5encryption(str);
           str=  "INSERT INTO `yonghu`(`id`,`username`,`password`) "
                 "VALUES (1,'admin',:s1)";
           query.prepare(str);
           query.bindValue(":s1",md5rslt);
           if(query.exec()){
               qDebug()<<"success to  insert admin";
           }else{
               qDebug()<<"fail to insert admin";
           }
        }
        else query1.exec();
    }
}

void MainWindow::on_pushButton_2_clicked()//注册新用户，在数据库中保存用户名和密码hash值
{
    if (!mainui_1->database.open())
    {
        qDebug() << "Error: Failed to connect database." << mainui_1->database.lastError();
    }
    else
    {
        //创建用户表
        QSqlQuery query1;
        QSqlQuery query2;
        if(ui->lineEdit->text().isEmpty()||ui->lineEdit_2->text().isEmpty()){//如果用户名或密码为空，提示错误信息
             QMessageBox::about(NULL, "输入错误", "重新输入");
            return;
        }
        if(mainui_1->database.tables().contains("yonghu")){        //存在用户信息表
        QString cipher=QCryptographicHash::hash(ui->lineEdit_2->text().toLatin1(),QCryptographicHash::Md5).toHex();
        query1.prepare(
                    "INSERT INTO `yonghu`(`id`,`username`,`password`) "
                               "VALUES (:s1,:s2,:s3)"
                    );
        query2.prepare("select count(id) from yonghu");
        int n;//记录总用户数
        if(!query2.exec())
        {
            qDebug()<<query2.lastError();
        }else{
            while(query2.next())
            {
              n=query2.value(0).toInt();
            }
        }
        query1.bindValue(":s1",n+1);//id
        query1.bindValue(":s2",ui->lineEdit->text());//用户名
        query1.bindValue(":s3",cipher);//密码hash值
        if(!query1.exec())
        {
            qDebug()<<query2.lastError();
        }else{
           QMessageBox::information(0,"infor","添加成功");
        }
    }
    }
}
